<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑个人资料"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="edit-profile-form"
    >
      <!-- 头像上传 -->
      <div class="avatar-upload-container">
        <el-upload
          class="avatar-uploader"
          action="#"
          :http-request="uploadAvatar"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.headshot" :src="form.headshot" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="avatar-tip">点击更换头像</div>
      </div>
      
      <!-- 基本信息 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { UserProfileApi } from '@/api/new/userProfleApi';
import UserUtil from '@/utils/User/User.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'updated']);

const dialogVisible = ref(props.visible);
const formRef = ref(null);
const loading = ref(false);

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
});

// 监听dialogVisible变化，同步回父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 表单数据
const form = reactive({
  userId: '',
  username: '',
  email: '',
  headshot: ''
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 初始化表单数据
const initFormData = () => {
  if (props.userData) {
    form.userId = props.userData.userID || '';
    form.username = props.userData.username || '';
    form.email = props.userData.email || '';
    form.headshot = props.userData.headshot || '';
  } else {
    // 如果没有传入用户数据，则使用当前登录用户的信息
    const currentUser = UserUtil.getUserInfo();
    if (currentUser) {
      form.userId = currentUser.userID || '';
      form.username = currentUser.username || '';
      form.email = currentUser.email || '';
      form.headshot = currentUser.headshot || '';
    }
  }
};

// 监听userData变化
watch(() => props.userData, () => {
  initFormData();
}, { deep: true });

// 组件挂载时初始化数据
onMounted(() => {
  initFormData();
});

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 上传头像
const uploadAvatar = async (options) => {
  try {
    // 这里应该调用实际的头像上传API
    // 由于没有具体的头像上传API，这里使用FileReader模拟
    const reader = new FileReader();
    reader.readAsDataURL(options.file);
    reader.onload = (e) => {
      form.headshot = e.target.result;
      ElMessage.success('头像上传成功');
    };
  } catch (error) {
    console.error('上传头像失败:', error);
    ElMessage.error('头像上传失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 调用更新用户信息API
        const response = await UserProfileApi.updateProfile(
          form.userId,
          form.username,
          form.email,
          form.headshot
        );
        
        // 更新本地存储的用户信息
        const currentUser = UserUtil.getUserInfo();
        if (currentUser && currentUser.userID === form.userId) {
          const updatedUser = {
            ...currentUser,
            username: form.username,
            email: form.email,
            headshot: form.headshot
          };
          UserUtil.setUserInfo(updatedUser);
        }
        
        ElMessage.success('个人资料更新成功');
        dialogVisible.value = false;
        emit('updated', {
          userID: form.userId,
          username: form.username,
          email: form.email,
          headshot: form.headshot
        });
      } catch (error) {
        console.error('更新个人资料失败:', error);
        ElMessage.error(error.message || '更新失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 对话框关闭后的处理
const handleClosed = () => {
  formRef.value?.resetFields();
};
</script>

<style lang="less" scoped>
.edit-profile-form {
  padding: 10px 20px;
  
  .avatar-upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    
    .avatar-uploader {
      width: 100px;
      height: 100px;
      border: 1px dashed #d9d9d9;
      border-radius: 50%;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;
      
      &:hover {
        border-color: #409EFF;
      }
      
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      
      .avatar-preview {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 50%;
      }
    }
    
    .avatar-tip {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 